using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Publicuse.Appication;
using Publicuse.Autofac;
using Publicuse.Cache;
using Publicuse.Entity;
using Publicuse.Util;
using ServiceStack;

namespace Publicuse.Application
{
  /// <summary>
  /// 消息通知管理
  /// </summary>
  public class NoticeanApplication
  {
    private static BaesApplication baseApplication;
    private static NoticeanApplication userApplication;

    public static NoticeanApplication GetApplication(ServiceContainer container)
    {
      baseApplication = new BaesApplication(container);
      return userApplication;
    }

    static NoticeanApplication()
    {
      userApplication = new NoticeanApplication();
    }

    /// <summary>
    /// 获取消息通知管理信息列表
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetList(Noticean query)
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var tableName = TableAtributeUtil.GetTable<Noticean>();
        string sql = query.GetQueryString<Noticean>(null);
        NoticeanQuery roleQuery = new NoticeanQuery()
        {
          tableName = tableName,
          sqlWhere = sql,
          sortFile = query.sortFile,
          sortType = query.sortType,
          files = query.files,
          pageIndex = query.pageIndex,
          pageSize = query.pageSize,
        };
        return baseApplication.GetList<Noticean>(roleQuery, false).GetAwaiter().GetResult();
      });
    }

    /// <summary>
    /// 获取消息通知管理详细信息
    /// </summary>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetDetail(int Id)
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var list = baseApplication.mySqlSugar.QueryByExpression<Noticean>(
          o => o.Id == Id,
          out var msg
        );
        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          var noticean = list.FirstOrDefault();
          result.data = noticean;
        }
        result.msg = msg;
        return result;
      });
    }

    /// <summary>
    /// 获取当前用户的消息通知管理信息列表
    /// </summary>
    /// <param name="nId"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetListc()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var LoginCode = HttpContextExtendBase.GetLoginCode();
        NoticeanDetail noticeanDetail = new NoticeanDetail();
        var list = baseApplication.mySqlSugar.QueryByExpression<Noticean>(
          o => o.status != -9,
          out var msg
        );
        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          noticeanDetail.alldata = list;
          var readornotlist = list.Where(o => o.readornot != "");
          if (readornotlist.Count() == 0)
          {
            noticeanDetail.unreaddata = list;
            noticeanDetail.readdata = new List<Noticean>();
          }
          else
          {
            List<Noticean> noticeans = new List<Noticean>();
            List<Noticean> noticeansb = new List<Noticean>();
            foreach (var item in list)
            {
              var readornotstrs = item.readornot.Split(',');
              if (!readornotstrs.Any(o => o == LoginCode))
              {
                noticeans.Add(item);
              }
              if (readornotstrs.Any(o => o == LoginCode))
              {
                noticeansb.Add(item);
              }
            }
            noticeanDetail.unreaddata = noticeans;
            noticeanDetail.readdata = noticeansb;
          }
        }
        result.data = noticeanDetail;
        result.msg = msg;
        return result;
      });
    }

    /// <summary>
    /// 获取当前用户未读的消息通知管理信息列表
    /// </summary>
    /// <param name="nId"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetListd()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var LoginCode = HttpContextExtendBase.GetLoginCode();
        NoticeanDetail noticeanDetail = new NoticeanDetail();
        var list = baseApplication.mySqlSugar.QueryByExpression<Noticean>(
          o => o.status != -9,
          out var msg
        );
        List<Noticean> noticeans = new List<Noticean>();
        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          var readornotlist = list.Where(o => o.readornot != "");
          if (readornotlist.Count() == 0)
          {
            noticeans = list;
          }
          else
          {
            foreach (var item in list)
            {
              var readornotstrs = item.readornot.Split(',');
              if (!readornotstrs.Any(o => o == LoginCode))
              {
                noticeans.Add(item);
              }
            }
          }
          noticeanDetail.unreaddata = noticeans;
        }
        result.count = noticeans.Count;
        result.data = noticeanDetail;
        result.msg = msg;
        return result;
      });
    }

    /// <summary>
    /// 检查数据是否存在
    /// </summary>
    /// <param name="title"></param>
    /// <param name="type"></param>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<CommonResult> CheckData(string title, string type, string Id = "")
    {
      return await baseApplication.CheckDataExists<Noticean>(
        BusinessType.noticean,
        BusinessLogType.writeLogToDataBase,
        o => o.title == title && o.type == type && o.status != -9,
        "检查数据是否存在",
        Id
      );
    }

    /// <summary>
    /// 赋值已读用户
    /// </summary>
    /// <param name="title"></param>
    /// <param name="type"></param>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<CommonResult> readuser(string title, string type, string Id = "")
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        if (!string.IsNullOrEmpty(title) && !string.IsNullOrEmpty(type))
        {
          var tableName = TableAtributeUtil.GetTable<Noticean>();
          var LoginCode = HttpContextExtendBase.GetLoginCode();
          var sql = $"select * from {tableName} where title=@title and type=@type;";
          var msg = string.Empty;
          var list = baseApplication.mySqlSugar.QueryBySqlPara<Noticean>(
            sql,
            new { title = title, type = type },
            out msg
          );
          if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
          {
            var data = list.FirstOrDefault().readornot;
            if (string.IsNullOrEmpty(data))
            {
              sql =
                $"update {tableName} set readornot=@readornot where title=@title and type=@type;";
              baseApplication.mySqlSugar.ExecuteSql(
                sql,
                new
                {
                  readornot = LoginCode,
                  title = title,
                  type = type
                },
                out msg
              );
            }
            else
            {
              var newreadornot = data + "," + LoginCode;
              newreadornot = string.Join(",", newreadornot.Split(',').Distinct());
              sql =
                $"update {tableName} set readornot=@readornot where title=@title and type=@type;";
              baseApplication.mySqlSugar.ExecuteSql(
                sql,
                new
                {
                  readornot = newreadornot,
                  title = title,
                  type = type
                },
                out msg
              );
            }
          }
          result.msg = msg;
        }
        return result;
      });
    }

    /// <summary>
    /// 获取未读信息
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResult> GetRead()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var table = TableAtributeUtil.GetTable<Noticean>();
        var LoginCode = HttpContextExtendBase.GetLoginCode();
        var sql = $"select * from {table} where status=2  order by cTime desc;";
        var list = baseApplication.mySqlSugar.Query<Noticean>(sql, null, out var msg);
        List<Noticean> resultdata = new List<Noticean>();
        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          foreach (var item in list)
          {
            if (string.IsNullOrEmpty(item.readornot))
            {
              item.status = 1;
              resultdata.Add(item);
            }
            else
            {
              if (!item.readornot.Contains(LoginCode))
              {
                item.status = 1;
                resultdata.Add(item);
              }
              else
              {
                item.status = 2;
                resultdata.Add(item);
              }
            }
          }
          var wdlist = resultdata.Where(o => o.status == 1);
          var ydlist = resultdata.Where(o => o.status == 2);
          result.count = resultdata.Count(o => o.status == 1);
          result.data = wdlist.Concat(ydlist);
        }
        result.msg = msg;
        return result;
      });
    }

    /// <summary>
    /// 批量审核数据
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<CommonResult> ConfirmAll(string data, string loginUserCode)
    {
      return await baseApplication.ConfirmAll<Noticean>(
        BusinessType.noticean,
        BusinessActionType.update,
        BusinessLogType.writeLogToDataBase,
        data,
        loginUserCode
      );
    }

    /// <summary>
    /// 审核数据
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<CommonResult> Confirm(string id, int type, string loginUserCode)
    {
      return await baseApplication.Confirm<Noticean>(
        BusinessType.noticean,
        BusinessActionType.update,
        BusinessLogType.writeLogToDataBase,
        id,
        type,
        loginUserCode
      );
    }

    /// <summary>
    /// 通知公告管理信息导入
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResult> ImportExcel(
      IFormFileCollection files,
      string path,
      string loginUserCode
    )
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult commonResult = new CommonResult();
        StringBuilder result = new StringBuilder();
        ImportResult importResult = new ImportResult();
        baseApplication.autofaceInstance.DoWork(
          BusinessType.noticean,
          BusinessActionType.import,
          files[0].FileName,
          "通知公告管理数据",
          BusinessLogType.writeLogToDataBase,
          (o) =>
          {
            commonResult = AddExcelToData(files, path);
            return commonResult;
          },
          null,
          ref commonResult
        );
        return commonResult;
      });
    }

    /// <summary>
    /// 从Excel中导入数据到数据库表
    /// </summary>
    private static CommonResult AddExcelToData(IFormFileCollection files, string path)
    {
      StringBuilder result = new StringBuilder();
      StringBuilder msgsb = new StringBuilder();
      ImportResult importResult = new ImportResult();
      CommonResult commonResult = new CommonResult();
      string msg = string.Empty;
      ImportCache.InitImportData(
        files,
        path,
        "消息通知管理",
        out msg,
        (list) =>
        {
          Dictionary<int, List<int>> aclist = new Dictionary<int, List<int>>();
          foreach (var dt in list) { }
          if (!string.IsNullOrEmpty(msg))
          {
            importResult.Remark = string.Format($"导入校验出错");
            commonResult.count = importResult.success;
            commonResult.data = importResult.Remark;
            commonResult.msg = msg;
            return false;
          }
          else
          {
            importResult.Remark = string.Format($"导入完成");
            commonResult.count = importResult.success;
            commonResult.data = importResult.Remark;
            return true;
          }
        }
      );
      return commonResult;
    }

    /// <summary>
    /// 新增修改消息通知管理信息
    /// </summary>
    /// <param name="Contacts"></param>
    /// <returns></returns>
    public async Task<CommonResult> AddOrUpdate(Noticean info)
    {
      if (!string.IsNullOrEmpty(info.readornotb))
      {
        info.readornot = info.readornotb;
      }
      return await baseApplication.AddOrUpdate<Noticean>(
        info,
        BusinessType.noticean,
        BusinessLogType.writeLogToDataBase
      );
    }

    /// <summary>
    /// 删除消息通知管理信息
    /// </summary>
    /// <param name="Id"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public async Task<CommonResult> Delete(string Id, string loginUserCode, string type)
    {
      return await baseApplication.Delete<Noticean>(
        Id,
        loginUserCode,
        type,
        BusinessType.noticean,
        (a, b, info) =>
        {
          return info.Id.ToString();
        }
      );
    }

    /// <summary>
    /// 还原消息通知管理信息
    /// </summary>
    /// <param name="Id"></param>
    /// <param name="loginUserCode"></param>
    /// <returns></returns>
    public async Task<CommonResult> Reduction(string Id, string loginUserCode)
    {
      return await baseApplication.Reduction<Noticean>(
        Id,
        loginUserCode,
        BusinessType.noticean,
        (a, b, info) =>
        {
          return info.Id.ToString();
        }
      );
    }
  }
}
